﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Raven.Client;
using Genrsis.WorkitemTracking.Domain;
using Genrsis.WorkitemTracking.Web.Models;

namespace Genrsis.WorkitemTracking.Web.Controllers
{
    public class WorkitemController : ControllerBase
    {
        public WorkitemController(IDocumentStore documentStore)
            : base(documentStore)
        {

        }

        [HttpGet]
        public ActionResult Index()
        {
            ViewBag.Title = Strings.Workitems;

            using (var session = DocumentStore.OpenSession())
            {
                var workitems = session.Query<Workitem>()
                    .ToList()
                    .Select(w => new WorkitemIndexViewModel
                    {
                        Id = w.Id,
                        Title = w.Title,
                        Description = w.Description,
                        StatusId = w.StatusId,
                        CreatedByUserId = w.CreatedByUserId,
                        WorkflowId = w.WorkflowId
                    });
                return View(workitems);
            }
        }

        [HttpGet]
        public ActionResult Create()
        {
            ViewBag.Title = Strings.Create;

            using (var session = DocumentStore.OpenSession())
            {
                var model = new WorkitemCreateViewModel
                {
                    StatusId = session.Query<Status>()
                        .Select(s => new SelectListItem
                        {
                            Value = s.Id,
                            Text = s.Name
                        }).ToList()
                };

                return View(model);
            }
        }

        [HttpPost]
        public ActionResult Create(WorkitemCreateViewModel model)
        {
            User user = GetCurrentUser();

            using (var session = DocumentStore.OpenSession())
            {
                Workitem workitem = user.CreateWorkitem(model.Title, model.Description, new Status(), user, new Workflow());
                session.Store(workitem);

                session.SaveChanges();
            }

            return RedirectToAction("Index");
        }
    }
}
